<?php
class Upload_Files_Model extends Model {
	
	function __construct()
	{
		parent::Model();
	}
	/*
	 * Upload files of diferent mime types by initialing the below values
	 * $config['allowed_types'] = 'gif|jpg|png'; 	or { mp3 , flv }
	 * $config['upload_path'] = './upload/'    don't forget to end upload path with slash
 	 * $config['max_size']	= '1000';
	 * $config['max_width']  = '1024';
	 * $config['max_height']  = '768';
	 * 
	 * $field name should be given 
	 * $field_name='image';  this name should be same as field name given in form
	 * $rename_to = "name_$id.jpg"
	 * $data = array(
	 * 					'rename_to'	=> "name_$id.jpg",
	 * 					
	 * );
	 */
	
	function Upload_Files($config = "", $field_name , $id = "",$data = array(),$is_thumb = FALSE)
	{
		$this->load->library('upload', $config);
	
		if ( ! $this->upload->do_upload($field_name))
		{
			$error[] = array('error' => $this->upload->display_errors());
			$this->session->set_flashdata('message',$error);
			$this->db->where('id', $id);
		 	$this->db->delete($data['update_table']);
			redirect($data['on_error_redirect']);
		}	
		else
		{
			$upload_data = array('upload_data' => $this->upload->data());
			
			if($data['rename_to']!="")
			{

				$filename = $config['upload_path'].$upload_data['upload_data']['file_name'];
				if(file_exists($filename))
				{
					$rename_to = $config['upload_path'].$data['rename_to'];
					if(file_exists($rename_to))
					{
						$this->delete_file($rename_to);
						$thumb_file = $config['upload_path'].$data['thumb_created'];
						$this->delete_file($thumb_file);
					}
				if(rename($filename,$rename_to))
				{
					if($is_thumb == TRUE)
					{
						$config['image_library'] = 'gd2';
						$config['source_image'] = $rename_to;
						$config['create_thumb'] = TRUE;
						$config['maintain_ratio'] = TRUE;
						$config['quality'] = '100%';
						$config['width'] = 139;
						$config['height'] = 105;
						
						$this->load->library('image_lib', $config); 
						
						$this->image_lib->resize();
					}
					$adata = array(
               				$data['update_column'] => 0,
            		);
            				$where = array('id'	=> $id);
							$result = $this->db->update($data['update_table'], $adata,$where);
							if($result >=1)
							return 'true';
							else 
							{
							$this->delete_file($rename_to);
							$this->db->where('id', $id);
		 					$this->db->delete($data['update_table']);
							return 'false';
							}
				}
				else 
				{
					$this->delete_file($filename);
					$this->db->where('id', $id);
		 			$this->db->delete($data['update_table']);
					return 'false';
				}
				}
			}	

		}
	 
	}
	
	function delete_file($filename){
		unlink($filename);
	}
	
}
?>